<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use Exception;

/**
 * 商品单位管理
 *
 * @icon fa fa-circle-o
 */
class Unit extends Backend
{

    /**
     * Unit模型对象
     * @var \app\common\model\product\Unit
     */
    protected $model = null;

    /**
     * 快速搜素
    */
    protected $searchFields = ['id','name'];

    /**
     * 开启Validate验证
     */
    // protected $modelValidate = true;

    public function _initialize()
    {
        parent::_initialize();

        // 模型
        $this->model = new \app\common\model\Product\Unit;

    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 商品单位列表
    */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);

        // 判断是否有Ajax请求
        if($this->request->isAjax())
        {
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            [$where, $sort, $order, $offset, $limit] = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            $result = ['total' => $list->total(), 'rows' => $list->items()];

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 新增商品单位
    */
    public function add()
    {
        if($this->request->isPost())
        {
            $params = $this->request->param('row/a');

            $data = [
                'name' => $params['name']
            ];

            $result = $this->model->validate('common/Product/Unit')->save($data);

            if($result === FALSE)
            {
                $this->error(__($this->model->getError()));
            }else{
                $this->success();
            }

        }
        return $this->view->fetch();
    }

    /**
     * 编辑商品单位
     * 
     * @param String $ids 主键
    */
    public function edit($ids = null)
    {
        $Unit = $this->model->get($ids);

        if(!$Unit)
        {
            $this->error(__('该商品单位不存在，请重新选择'));
        }

        if($this->request->isPost())
        {
            $params = $this->request->param('row/a');

            $data = [
                'id' => $ids,
                'name' => $params['name']
            ];

            $result = $this->model->validate('common/Product/Unit')->isUpdate(true)->save($data);

            if($result === FALSE)
            {
                $this->error(__($this->model->getError()));
            }else{
                $this->success();
            }
        }

        $data = [
            'row' => $Unit
        ];

        return $this->view->fetch('',$data);
    }

    /**
     * 删除商品单位
     * 
     * @param String $ids 主键
     * 
    */
    public function del($ids = null)
    {
        $idArr = !empty($ids) ? explode(',',$ids) : [];

        if(empty($idArr))
        {
            $this->error(__('请选择需要删除商品单位'));
        }

        $list = $this->model->where('id','in',$idArr)->select();

        $count = 0;

        // 开启事务
        Db::startTrans();

        try {
            foreach ($list as $item) {
                $count += $item->delete();
            }

            // 提交事务
            Db::commit();

        } catch (PDOException|Exception $e) {
            // 事务回滚
            Db::rollback();

            // 获取错误信息
            $this->error($e->getMessage());
        }
        if ($count) {
            
            $this->success();
        }
    }
}
